package cz.boxdesign.library.configuration;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import cz.boxdesign.vizitky.service.CardService;
import cz.boxdesign.vizitky.service.CardServiceImpl;
import cz.boxdesign.vizitky.web.InitController;

@Configuration
@PropertySource("classpath:/common-globals.properties")
public class AppConfig {

  @Autowired
  Environment env;

  @Bean
  public InternalResourceViewResolver configureInternalResourceViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    return resolver;
  }

  @Bean
  public ResourceBundleMessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    String[] beanNames = { "common-globals", "common-global-label",
          "messages", "entity-label" };
    messageSource.setBasenames(beanNames);
    return messageSource;
  }

  @Bean
  public DatabaseOperation databaseOperation() {
    try {
      Class.forName(env.getProperty("jdbc.driverClassName"));
      Connection connection;
      String url = env.getProperty("jdbc.url");
      connection = DriverManager.getConnection(url, env.getProperty("jdbc.user"), env.getProperty("jdbc.password"));
      return new DatabaseOperation(connection,env.getProperty("jdbc.driverClassName"),url, env.getProperty("jdbc.user"), env.getProperty("jdbc.password"));
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Bean
  public CardService cardService() {
    CardServiceImpl cs = new CardServiceImpl();
    cs.setName(env.getProperty("card.service.name"));
    return cs;
  }

  @Bean
  public InitController initController() {
    InitController initController = new InitController();
    return initController;
  }

}
